from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QLabel

from common.utils.design_pattern.observe_pattern import Observer
from ui.base.widgets.labeled_widget import SettingSplitter
from ui.system_status import SystemStatus

color_list = ["yellow", "red", "green"]


class InfoWidget(SettingSplitter, Observer):
    def __init__(self, key_text, value_text, resource_key=None, orientation=Qt.Horizontal, parent=None):
        super(InfoWidget, self).__init__(parent)
        self.resource_key = resource_key
        self.setOrientation(orientation)
        self.setChildrenCollapsible(False)
        self.setHandleWidth(0)
        self.key_label = QLabel(key_text, parent)
        self.value_label = QLabel(parent)
        self.addWidget(self.key_label)
        self.addWidget(self.value_label)
        self.set_value_label_text(value_text)
        self.font = QFont()
        self.font.setBold(True)
        self.font.setPointSize(15)

    def set_value_label_text(self, text):
        for color in color_list:
            color_prefix = f"{color}:"
            if color_prefix in text:
                return self.set_text_color(self.value_label, text.replace(color_prefix, "").strip(), color)
        if text == "NG":
            color = "red"
        elif text == "OK":
            color = "green"
        else:
            color = "black"
        self.set_text_color(self.value_label, text, color)

    def set_text_color(self, obj, text, color):
        text = f'<span style="color: {color}">{text}</span>'
        obj.setText(text)

    def set_font_size(self, font_size):
        self.font.setPointSize(font_size)
        self.key_label.setFont(self.font)
        self.value_label.setFont(self.font)

    def update_status(self, observable, extra_data=None):
        """
        根据数据更新界面
        @param observable:
        @param extra_data:
        @return:
        """
        if self.resource_key in extra_data:
            value = extra_data[self.resource_key]
            if value is not None:
                self.set_value_label_text(str(value))
            # else:
            #     self.set_value_label_text("--")
